package org.example.onlinejudge.controller;

import org.example.onlinejudge.model.Role;
import org.example.onlinejudge.service.RoleService;
import org.example.onlinejudge.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 管理员角色管理控制器
 */
@Controller
@RequestMapping("/admin/roles")
@PreAuthorize("hasRole('0')") // 仅管理员可访问
public class AdminRoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 角色列表页面
     */
    @GetMapping
    // @PreAuthorize("hasAuthority('role:view')") // 临时注释掉，用于调试
    public String roleList(Model model) {
        System.out.println("\n========== 访问角色管理页面 ==========");
        
        var roles = roleService.findAllRoles();
        var permissions = permissionService.findAllPermissions();
        
        System.out.println("✓ 查询到角色数量: " + roles.size());
        System.out.println("✓ 查询到权限数量: " + permissions.size());
        
        model.addAttribute("roles", roles);
        model.addAttribute("allPermissions", permissions);
        
        System.out.println("✓ 返回模板: admin/roles");
        System.out.println("========== 处理完成 ==========\n");
        
        return "admin/roles";
    }

    /**
     * 添加角色
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('role:add')")
    public String addRole(@RequestParam("roleCode") String roleCode,
                         @RequestParam("roleName") String roleName,
                         RedirectAttributes redirectAttributes) {
        try {
            roleService.createRole(roleCode, roleName);
            redirectAttributes.addFlashAttribute("success", "角色添加成功");
            return "redirect:/admin/roles";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "添加失败：" + e.getMessage());
            return "redirect:/admin/roles";
        }
    }

    /**
     * 编辑角色
     */
    @PostMapping("/edit/{id}")
    @PreAuthorize("hasAuthority('role:edit')")
    public String editRole(@PathVariable Long id,
                          @RequestParam("roleName") String roleName,
                          RedirectAttributes redirectAttributes) {
        try {
            roleService.updateRole(id, roleName);
            redirectAttributes.addFlashAttribute("success", "角色更新成功");
            return "redirect:/admin/roles";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新失败：" + e.getMessage());
            return "redirect:/admin/roles";
        }
    }

    /**
     * 删除角色
     */
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('role:delete')")
    public String deleteRole(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            roleService.deleteRole(id);
            redirectAttributes.addFlashAttribute("success", "角色删除成功");
            return "redirect:/admin/roles";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除失败：" + e.getMessage());
            return "redirect:/admin/roles";
        }
    }

    /**
     * 为角色添加权限
     */
    @PostMapping("/add-permission/{roleId}")
    @PreAuthorize("hasAuthority('role:edit')")
    public String addPermissionToRole(@PathVariable Long roleId,
                                     @RequestParam("permissionId") Long permissionId,
                                     RedirectAttributes redirectAttributes) {
        try {
            roleService.addPermissionToRole(roleId, permissionId);
            redirectAttributes.addFlashAttribute("success", "权限添加成功");
            return "redirect:/admin/roles";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "权限添加失败：" + e.getMessage());
            return "redirect:/admin/roles";
        }
    }

    /**
     * 从角色移除权限
     */
    @PostMapping("/remove-permission/{roleId}")
    @PreAuthorize("hasAuthority('role:edit')")
    public String removePermissionFromRole(@PathVariable Long roleId,
                                          @RequestParam("permissionId") Long permissionId,
                                          RedirectAttributes redirectAttributes) {
        try {
            roleService.removePermissionFromRole(roleId, permissionId);
            redirectAttributes.addFlashAttribute("success", "权限移除成功");
            return "redirect:/admin/roles";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "权限移除失败：" + e.getMessage());
            return "redirect:/admin/roles";
        }
    }
}
